package com.px.web.controller.service;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.px.service.domain.*;
import com.px.service.service.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.px.common.annotation.Log;
import com.px.common.core.controller.BaseController;
import com.px.common.core.domain.AjaxResult;
import com.px.common.enums.BusinessType;
import com.px.common.utils.poi.ExcelUtil;
import com.px.common.core.page.TableDataInfo;

/**
 * 纪念馆Controller
 *
 * @author 品讯科技
 * @date 2024-08
 */
@RestController
@RequestMapping("/service/hall")
public class MemorialHallController extends BaseController {

    @Autowired
    private IMemorialHallService memorialHallService;
    @Autowired
    private IMusicService mMusicService;
    @Autowired
    private IIndexBackgroundService mIndexBackgroundService;
    @Autowired
    private IWorshipBackgroundService mWorshipBackgroundService;
    @Autowired
    private IDeceasedService mDeceasedService;
    @Autowired
    private ILifeStoryService mLifeStoryService;
    @Autowired
    private ILifeStoryPictureService mLifeStoryPictureService;

    /**
     * 查询纪念馆列表
     */
    @PreAuthorize("@ss.hasPermi('service:hall:list')")
    @GetMapping("/list")
    public TableDataInfo list(MemorialHall memorialHall) {
        startPage();
        List<MemorialHall> list = memorialHallService.selectMemorialHallList(memorialHall);
        return getDataTable(list);
    }

    /**
     * 导出纪念馆列表
     */
    @PreAuthorize("@ss.hasPermi('service:hall:export')")
    @Log(title = "纪念馆", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MemorialHall memorialHall) {
        List<MemorialHall> list = memorialHallService.selectMemorialHallList(memorialHall);
        ExcelUtil<MemorialHall> util = new ExcelUtil<MemorialHall>(MemorialHall.class);
        util.exportExcel(response, list, "纪念馆数据");
    }

    /**
     * 获取纪念馆详细信息
     */
    @PreAuthorize("@ss.hasPermi('service:hall:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(memorialHallService.selectMemorialHallById(id));
    }

    /**
     * 新增纪念馆
     */
    @PreAuthorize("@ss.hasPermi('service:hall:add')")
    @Log(title = "纪念馆", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MemorialHall memorialHall) {
        String createBy = getLoginUser().getUserId().toString();
        // 设置默认背景音乐
        Music music = new Music();
        music.setIsDefault(1L);
        List<Music> musicList = mMusicService.selectMusicList(music);
        if (musicList.size() > 0) {
            memorialHall.setMusicId(musicList.get(0).getMusicId());
        }
        // 设置纪念馆默认背景图片
        IndexBackground indexBackground = new IndexBackground();
        indexBackground.setIsDefault(1L);
        List<IndexBackground> indexBackgroundList = mIndexBackgroundService.selectIndexBackgroundList(indexBackground);
        if (indexBackgroundList.size() > 0) {
            memorialHall.setIndexBackgroundId(indexBackgroundList.get(0).getIndexBackgroundId());
        }
        // 设置祭扫默认背景图片
        WorshipBackground worshipBackground = new WorshipBackground();
        worshipBackground.setIsDefault(1L);
        List<WorshipBackground> worshipBackgroundList = mWorshipBackgroundService.selectWorshipBackgroundList(worshipBackground);
        if (worshipBackgroundList.size() > 0) {
            memorialHall.setWorshipBackgroundId(worshipBackgroundList.get(0).getWorshipBackgroundId());
        }
        // 设置默认纪念馆名称
        StringBuilder name = new StringBuilder();
        for (int i = 0; i < memorialHall.getDeceaseds().size(); i++) {
            if (i > 0) {
                name.append("&");
            }
            name.append(memorialHall.getDeceaseds().get(i).getName());
        }
        memorialHall.setName(name.toString());
        // 创建者
        memorialHall.setCreateBy(createBy);
        // 创建名人馆自动生成密钥用于绑定管理员
        if (memorialHall.getType() == 1) {
            memorialHall.setFamousKey(UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16) + String.valueOf(System.currentTimeMillis()));
        }
        // 插入纪念馆信息
        memorialHallService.insertMemorialHall(memorialHall);
        // 插入逝者信息
        for (Deceased deceased : memorialHall.getDeceaseds()) {
            deceased.setHallId(memorialHall.getId());
            deceased.setCreateBy(createBy);
            mDeceasedService.insertDeceased(deceased);
        }
        return AjaxResult.success(memorialHall);
    }

    /**
     * 修改纪念馆
     */
    @PreAuthorize("@ss.hasPermi('service:hall:edit')")
    @Log(title = "纪念馆", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MemorialHall memorialHall) {
        Deceased param = new Deceased();
        param.setHallId(memorialHall.getId());
        List<Deceased> oldDeceaseds = mDeceasedService.selectDeceasedList(param);
        // 删减逝者信息
        if (oldDeceaseds.size() > memorialHall.getDeceaseds().size()) {
            List<Deceased> delList = oldDeceaseds.stream().filter(item -> memorialHall.getDeceaseds().stream().noneMatch(deceased -> deceased.getId().equals(item.getId()))).collect(Collectors.toList());
            for (Deceased deceased : delList) {
                // 删除生平事迹图片
                LifeStory lParam = new LifeStory();
                lParam.setDeceasedId(deceased.getId());
                List<LifeStory> lifeStories = mLifeStoryService.selectLifeStoryList(lParam);
                for (LifeStory lifeStory : lifeStories) {
                    mLifeStoryPictureService.deleteLifeStoryPictureByStoryId(lifeStory.getId());
                }
                // 删除生平事迹
                mLifeStoryService.deleteLifeStoryByDeceasedId(deceased.getId());
                // 删除逝者
                mDeceasedService.deleteDeceasedById(deceased.getId());
            }
        }

        for (Deceased deceased : memorialHall.getDeceaseds()) {
            if (deceased.getId() != null) {
                mDeceasedService.updateDeceased(deceased);
            } else {
                deceased.setHallId(memorialHall.getId());
                deceased.setCreateBy(getLoginUser().getUserId().toString());
                mDeceasedService.insertDeceased(deceased);
            }
        }
        // 设置默认纪念馆名称
        StringBuilder name = new StringBuilder();
        for (int i = 0; i < memorialHall.getDeceaseds().size(); i++) {
            if (i > 0) {
                name.append("&");
            }
            name.append(memorialHall.getDeceaseds().get(i).getName());
        }
        memorialHall.setName(name.toString());
        memorialHallService.updateMemorialHall(memorialHall);
        return AjaxResult.success();
    }

    /**
     * 删除纪念馆
     */
    @PreAuthorize("@ss.hasPermi('service:hall:remove')")
    @Log(title = "纪念馆", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        MemorialHall memorialHall = new MemorialHall();
        memorialHall.setId(id);
        memorialHall.setIsDelete(1);
        return toAjax(memorialHallService.updateMemorialHall(memorialHall));
    }

    /**
     * 修改纪念馆设置
     */
    @PreAuthorize("@ss.hasPermi('service:hall:edit')")
    @Log(title = "修改纪念馆设置", businessType = BusinessType.UPDATE)
    @PutMapping("/setting")
    public AjaxResult setOpen(@RequestBody MemorialHall memorialHall) {
        if (memorialHall.getStatus() == 1) {
            memorialHall.setVerifyMessage("");
        }
        return toAjax(memorialHallService.updateMemorialHall(memorialHall));
    }
}
